//
//  TrainController.m
//  EagleEye
//
//  Created by 18_李明明 on 15-1-20.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "TrainController.h"
#import "NetHander.h"
#import "TrainTableViewCell.h"
#import "DataBaseHandler.h"
@interface TrainController ()<UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UIScrollView *trainScrollView;
@property (nonatomic, strong) UISegmentedControl *trainSegment;
// 第一页
@property (nonatomic, strong) UITextField *trainNumber;
@property (nonatomic, strong) UIButton *trainQuery;
@property (nonatomic, strong) UITableView *trainTableView;
@property (nonatomic, strong) NSArray *trainContent;
// 第二页
@property (nonatomic, strong) UITextField *from;
@property (nonatomic, strong) UITextField *to;
@property (nonatomic, strong) UIButton *ThreadQuery;
@property (nonatomic, strong) UITableView *stateTableView;
@property (nonatomic, strong) NSArray *stateContent;
// 数据库
@property (nonatomic, strong) DataBaseHandler *dataBase;
@end

@implementation TrainController
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.trainContent = [NSArray array];
        self.stateContent = [NSArray array];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataBase = [DataBaseHandler shareInstance];
    
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    NSArray *arr = [NSArray arrayWithObjects:@"车次查询", @"站站查询", nil];
    self.trainSegment = [[UISegmentedControl alloc] initWithItems:arr];
    self.trainSegment.selectedSegmentIndex = 0;
    self.trainSegment.frame = CGRectMake(0, 20, WIDTH, 40);
    [self.view addSubview:self.trainSegment];
    [self.trainSegment addTarget:self action:@selector(targetSegment:) forControlEvents:UIControlEventValueChanged];
    // 添加scrollview
    self.trainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 60, WIDTH, HEIGHT - 104)];
    self.trainScrollView.contentSize = CGSizeMake(WIDTH * 2, 0);
    self.trainScrollView.pagingEnabled = YES;
    self.trainScrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.trainScrollView];
    self.trainScrollView.delegate = self;
    // 添加一个返回的按钮
    UIButton *cancle = [UIButton buttonWithType:UIButtonTypeSystem];
    cancle.frame = CGRectMake(0, HEIGHT - 40, 40, 30);
//    [cancle setTitle:@"返回" forState:UIControlStateNormal];
    [cancle setBackgroundImage:[UIImage imageNamed:@"cancle.png"] forState:UIControlStateNormal];
    cancle.tag = 502;
    [self.view addSubview:cancle];
    [cancle addTarget:self action:@selector(targetCancle:) forControlEvents:UIControlEventTouchUpInside];
    [self firstPage];
    [self secondPage];
}
// 返回按钮方法
- (void)targetCancle:(UIButton *)cancle
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


// 第一页
- (void)firstPage
{
    // 创建输入框
    self.trainNumber = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, WIDTH * 2 / 3, 40)];
    self.trainNumber.placeholder = @"请输入车次";
    self.trainNumber.borderStyle = UITextBorderStyleRoundedRect;
    [self.trainScrollView addSubview:self.trainNumber];
    // 创建按钮
    self.trainQuery = [UIButton buttonWithType:UIButtonTypeSystem];
    self.trainQuery.frame = CGRectMake(WIDTH * 2 / 3, 0, WIDTH / 3, 40);
    [self.trainQuery setTitle:@"查询" forState:UIControlStateNormal];
    [self.trainQuery addTarget:self action:@selector(targetQuery:) forControlEvents:UIControlEventTouchUpInside];
    [self.trainScrollView addSubview:self.trainQuery];
    // 创建tableview
    self.trainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 50, WIDTH, HEIGHT - 104) style:UITableViewStyleGrouped];
    self.trainTableView.dataSource = self;
    self.trainTableView.delegate = self;
    self.trainTableView.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"trainroad.jpg"]];
    [self.trainScrollView addSubview:self.trainTableView];
    if (self.line.length != 0) {
        UIButton *button = (UIButton *)[self.view viewWithTag:502];
        [button removeFromSuperview];
        self.trainTableView.frame = CGRectMake(0, 50, WIDTH, HEIGHT - 160);
         self.stateTableView.frame = CGRectMake(WIDTH, 80, WIDTH, HEIGHT - 200);
        self.trainNumber.text = self.line;
        self.trainScrollView.contentOffset = CGPointMake(0, 0);
        self.trainSegment.selectedSegmentIndex = 0;
        [self querySelect];
    }
    
}
- (void)targetQuery:(UIButton *)query
{
    [self.trainNumber resignFirstResponder];
    if (self.trainNumber.text.length != 0) {
        [self.dataBase openDB];
        [self.dataBase createTrainOfLine];
        [self.dataBase insertTrainOfLine:self.trainNumber.text];
    }
    [self querySelect];
}
- (void)querySelect
{
    NSString *path = [NSString stringWithFormat:@"http://apps.virsir.com/train_query_timetable?api=2&id=%@&date=2015-1-19&lang=en_us", self.trainNumber.text];
    [NetHander getDataWithUrl:path completion:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.trainContent = [dic objectForKey:@"stations"];
        [self.trainTableView reloadData];
    }];
}
#pragma mark 第二页
- (void)secondPage{
    // 创建两个输入框
    self.from = [[UITextField alloc] initWithFrame:CGRectMake(WIDTH, 0, WIDTH * 2 / 3, 40)];
    self.from.placeholder = @"起点";
    self.from.borderStyle = UITextBorderStyleRoundedRect;
    [self.trainScrollView addSubview:self.from];
    
    self.to = [[UITextField alloc] initWithFrame:CGRectMake(WIDTH, 40, WIDTH * 2 / 3, 40)];
    self.to.placeholder = @"终点";
    self.to.borderStyle = UITextBorderStyleRoundedRect;
    [self.trainScrollView addSubview:self.to];
    // 创建一个查询按钮
    self.ThreadQuery = [UIButton buttonWithType:UIButtonTypeSystem];
    self.ThreadQuery.frame = CGRectMake(WIDTH * 5 / 3, 0, WIDTH / 3, 80);
    [self.ThreadQuery setTitle:@"查询" forState:UIControlStateNormal];
    [self.trainScrollView addSubview:self.ThreadQuery];
    [self.ThreadQuery addTarget:self action:@selector(targetThread:) forControlEvents:UIControlEventTouchUpInside];
    // 创建一个tableview
    self.stateTableView = [[UITableView alloc] initWithFrame:CGRectMake(WIDTH, 80, WIDTH, HEIGHT - 144) style:UITableViewStyleGrouped];
    self.stateTableView.delegate = self;
    self.stateTableView.dataSource = self;
    self.stateTableView.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"train.jpg"]];
    [self.trainScrollView addSubview:self.stateTableView];
    if (self.fromStation.length != 0) {
        UIButton *button = (UIButton *)[self.view viewWithTag:502];
        [button removeFromSuperview];
        self.stateTableView.frame = CGRectMake(WIDTH, 80, WIDTH, HEIGHT - 200);
         self.trainTableView.frame = CGRectMake(0, 50, WIDTH, HEIGHT - 160);
        self.from.text = self.fromStation;
        self.to.text = self.toStation;
        [self threadSelect];
        self.trainSegment.selectedSegmentIndex = 1;
        self.trainScrollView.contentOffset = CGPointMake(WIDTH, 0);
    }
}
- (void)targetThread:(UIButton *)thread
{
    
    [self.from resignFirstResponder];
    [self.to resignFirstResponder];
    if (self.from.text.length != 0 && self.to.text.length != 0) {
        NSString *tempStr = [self.from.text stringByAppendingString:self.to.text];
        [self.dataBase openDB];
        [self.dataBase createTrainOfChange];
        [self.dataBase insertTrainOfFrom:self.from.text to:self.to.text combine:tempStr];
    }
    [self threadSelect];
}
- (void)threadSelect
{
    NSString *path = [NSString stringWithFormat:@"http://apps.virsir.com/train_query_timetable?api=2&from=%@&to=%@&date=&lang=en_us", self.from.text, self.to.text];
    [NetHander getDataWithUrl:path completion:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.stateContent = [dic objectForKey:@"items"];
        [self.stateTableView reloadData];
    }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.trainSegment.selectedSegmentIndex == 0) {
        return self.trainContent.count;
    }else {
        return self.stateContent.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.trainSegment.selectedSegmentIndex == 0) {
        TrainTableViewCell *cell = [self.trainTableView dequeueReusableCellWithIdentifier:@"0502"];
        if (cell == nil) {
            cell = [[TrainTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"0502"];
        }
//        cell.textLabel.text = [[self.trainContent objectAtIndex:indexPath.row] objectForKey:@"name"];
        if (self.trainNumber.text.length != 0) {
            cell.station.text = [[self.trainContent objectAtIndex:indexPath.row] objectForKey:@"name"];
            NSString *tempStr = [NSString stringWithFormat:@"%@ - %@", [[self.trainContent objectAtIndex:indexPath.row] objectForKey:@"comeTime"], [[self.trainContent objectAtIndex:indexPath.row] objectForKey:@"leaveTime"]];
            cell.time.text = tempStr;
            //        cell.detailTextLabel.text = tempStr;
            NSString *stop = [[self.trainContent objectAtIndex:indexPath.row] objectForKey:@"comeTime"];
            NSArray *stopArr = [stop componentsSeparatedByString:@":"];
            NSInteger stopTime = [[stopArr firstObject] integerValue] * 60 + [[stopArr lastObject] integerValue];
            NSString *start = [[self.trainContent objectAtIndex:indexPath.row] objectForKey:@"leaveTime"];
            NSArray *startArr = [start componentsSeparatedByString:@":"];
            NSInteger startTime = [[startArr firstObject] integerValue] * 60 + [[startArr lastObject] integerValue];
            cell.during.text = [NSString stringWithFormat:@"%ld", startTime - stopTime];
            if (indexPath.row == 0 || indexPath.row == self.trainContent.count - 1) {
                cell.during.text = nil;
            }
        }
        return cell;
    }else {
        UITableViewCell *cell = [self.stateTableView dequeueReusableCellWithIdentifier:@"0502"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"0502"];
        }
        if (self.stateContent.count != 0) {
        cell.textLabel.text = [[self.stateContent objectAtIndex:indexPath.row] objectForKey:@"id"];
        }
        return cell;
    }
}
// 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.trainSegment.selectedSegmentIndex == 1) {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        self.trainSegment.selectedSegmentIndex = 0;
        self.trainScrollView.contentOffset = CGPointMake(0, 0);
        self.trainNumber.text = cell.textLabel.text;
        [self targetQuery:self.trainQuery];
    }
}
// 设置section的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}
// http://app.cheyooh.com/i.ashx?m=wz_v2&uid=1e4220f81b7c42b798f20373ab920beb&ver=1.1.0&channel=F004应用汇V1.1.0&key=5ffb15e270e65953cbbb89286d92076e&tagversion=cyh?&vao=武汉&lpn=鄂A7LT67&phone=&vfn=102554
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)targetSegment:(UISegmentedControl *)segment
{
    self.trainScrollView.contentOffset = CGPointMake(WIDTH * segment.selectedSegmentIndex, 0);
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.trainSegment.selectedSegmentIndex = self.trainScrollView.contentOffset.x / WIDTH;
}
- (void) scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.trainNumber resignFirstResponder];
    [self.from resignFirstResponder];
    [self.to resignFirstResponder];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
